<?php
namespace app\supplier\shophttp;

use app\supplier\common\ApiHttp;
use think\facade\Cache;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Utils;
use GuzzleHttp\Client;

class Base
{

    private static $instance;
    protected $access_token;
    protected $baseUrl = 'https://shop.jzzw-tech.cn';
    public static function getInstance($appid, $appsecret)
    {
        if (static::$instance === null) {
            static::$instance = new static();
            static::$instance->access_token = static::$instance->AccessToken($appid, $appsecret);
        }
        return static::$instance;
    }

    public function getAccessToken()
    {
        return $this->access_token;
    }
    /**
     * 搜索获取一个员工二维码
     */
    private function AccessToken($appid, $appsecret)
    {
        $CacheKey = base64_encode($appid . $appsecret);
        $AccessToken = Cache::get($CacheKey);
        if (!$AccessToken) {
            $url = $this->baseUrl . '/outapi/access_token';
            $response = $this->require($url, [
                "appid" => $appid,
                "appsecret" => $appsecret,
            ], 'POST', [], false);

            if ($response['status'] == 200) {
                Cache::set($CacheKey, $response['data']['access_token'], $response['data']['exp_time']);
                return $response['data']['access_token'];
            } else {
                throw new \Exception($response['msg'], 1);
            }

        }
        return $AccessToken;
    }

    protected function require($url = '', $body = [], $method = 'POST', $headers = [], $isToken = true)
    {
        $client = new Client(['verify' => dirname(__FILE__) . DIRECTORY_SEPARATOR . 'cacert.pem',]);
        if ($isToken) {
            $headers['Authori-Zation'] = 'Bearer ' . $this->access_token;
        }
        $headers['content-type'] = 'application/json;charset=utf-8';
        // $headers['content-type'] = 'multipart/form-data;charset=utf-8';

        $body = json_encode($body, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);


        $request = new Request($method, $url, $headers, $body);
        $res = $client->sendAsync($request)->wait();
        $res = $res->getBody()->getContents();
        return json_decode($res, true);
    }
    protected function get($url, $body = [], $headers = [], $isToken = true)
    {
        return $this->require($url, $body, 'GET', $headers, $isToken);
    }
    protected function post($url, $body = [], $headers = [], $isToken = true)
    {
        return $this->require($url, $body, 'POST', $headers, $isToken);
    }
    protected function put($url, $body = [], $headers = [], $isToken = true)
    {
        return $this->require($url, $body, 'PUT', $headers, $isToken);
    }
}